package com.yoke.common;

import com.yoke.system.SystemBean;
import com.yoke.system.log.SystemLog;
import com.yoke.util.StringUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/5/9.
 */
public class UserUtil {

    private static final File file = new File(new File(SystemBean.getInstance().VelocityPath).getParentFile(), "user.conf");

    public static boolean login(String name, String pwd) {
        if (!file.exists())
            throw new RuntimeException("请联系管理员");
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String[] info = StringUtil.StringToArray(line, ":");
                if (info == null || info.length != 2)
                    continue;
                if (info[0].equals(name) && info[1].equals(pwd))
                    return true;
            }
            return false;
        } catch (IOException e) {
            SystemLog.ERROR().error("读取密码错误", e);
            throw new RuntimeException("请联系管理员");
        } finally {
            if (bufferedReader != null)
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    SystemLog.ERROR().error(e.getLocalizedMessage(), e);
                }
        }
    }

    public static boolean check(String name) {
        if (!file.exists())
            throw new RuntimeException("请联系管理员");
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String[] info = StringUtil.StringToArray(line, ":");
                if (info == null || info.length != 2)
                    continue;
                if (info[0].equals(name))
                    return true;
            }
            return false;
        } catch (IOException e) {
            SystemLog.ERROR().error("读取密码错误", e);
            throw new RuntimeException("请联系管理员");
        } finally {
            if (bufferedReader != null)
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    SystemLog.ERROR().error(e.getLocalizedMessage(), e);
                }
        }
    }
}
